import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

import '../widgets/like_button.dart';

class PostGridViewSimple extends StatelessWidget {
  final List<Map<String, dynamic>> posts;

  const PostGridViewSimple({super.key, required this.posts});

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    final paddingHorizontal = 12 * 2; // SliverPadding
    final crossAxisSpacing = 6.0;
    final crossAxisCount = 2;

    final totalSpacing =
        paddingHorizontal + crossAxisSpacing * (crossAxisCount - 1);
    final itemWidth = (screenWidth - totalSpacing) / crossAxisCount;

    const textHeight = 60.0;
    final itemHeight = itemWidth + textHeight;
    final childAspectRatio = itemWidth / itemHeight;

    return SliverGrid(
      delegate: SliverChildBuilderDelegate((context, index) {
        final post = posts[index];
        final images =
            post['images'] != null && post['images'].toString().startsWith('[')
            ? List<String>.from(jsonDecode(post['images']))
            : [];

        final String userNickname = post['nickname'] ?? '匿名用户';
        final int likeCount = post['likeCount'] ?? 0;
        final bool liked = post['liked'] ?? false;

        return GestureDetector(
          onTap: () {
            context.pushNamed(
              'postDetail',
              pathParameters: {'id': post['id'].toString()},
            );
          },
          child: Container(
            margin: EdgeInsets.zero,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
              boxShadow: const [
                BoxShadow(
                  color: Colors.black12,
                  blurRadius: 4,
                  offset: Offset(1, 2),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                AspectRatio(
                  aspectRatio: 1,
                  child: ClipRRect(
                    borderRadius: const BorderRadius.vertical(
                      top: Radius.circular(8),
                    ),
                    child: buildImageWidget(
                      images.isNotEmpty && images.first.isNotEmpty
                          ? images.first
                          : null,
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 6,
                    vertical: 2,
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Text(
                        post['title'] ?? '',
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Row(
                        children: [
                          Expanded(
                            child: Text(
                              userNickname,
                              style: const TextStyle(
                                fontSize: 12,
                                color: Colors.grey,
                              ),
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                          LikeButton(postId: post['id'].toString()),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      }, childCount: posts.length),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: crossAxisCount,
        mainAxisSpacing: crossAxisSpacing,
        crossAxisSpacing: crossAxisSpacing,
        childAspectRatio: childAspectRatio,
      ),
    );
  }
}

Widget buildImageWidget(String? imageUrl) {
  if (imageUrl == null || imageUrl.isEmpty) {
    // 没有网络图片，直接显示本地默认图
    return Image.asset('assets/default_bg_compressed.webp', fit: BoxFit.cover);
  }

  // 有网络图片，尝试加载，失败时显示本地默认图和错误图标
  return Image.network(
    imageUrl,
    fit: BoxFit.cover,
    errorBuilder: (context, error, stackTrace) {
      // 加载失败显示默认图和错误图标
      return Stack(
        fit: StackFit.expand,
        children: [
          Image.asset('assets/default_bg.png', fit: BoxFit.cover),
          Container(
            color: Colors.black26,
            alignment: Alignment.center,
            child: const Icon(
              Icons.broken_image,
              size: 40,
              color: Colors.white70,
            ),
          ),
        ],
      );
    },
  );
}
